﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CandyAdmin.Areas.Admin.Models;
using CandyAdmin.Config.Filters;
using Microsoft.AspNetCore.Mvc;
using Services;
using Microsoft.AspNetCore.Http;
using Entites;
using IServices;

namespace CandyAdmin.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class UserController : Controller
    {
        IUserApp _user;
        public UserController(IUserApp user)
        {
            this._user = user;
        
        }
        public IActionResult Index()
        {
            return View();
        }
       
       [PublicAccess]
       [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [PublicAccess]
        [HttpPost]
        public IActionResult doLogin([FromBody]LoginModel u)
        {
            var ot = HttpContext.Request;
            if(HttpContext.Session.GetString("user")!=null)
                return RedirectToAction("Index", "Home");
            if (u != null)
            {
                var db = _user.GetDb();
                var os = db.LoadListAll(m=>m.username!=null).Count();
               

                var oo = db.IsExist(o => o.username == u.username && o.paswword == u.password);
                if (oo == true)
                {
                    HttpContext.Session.SetString("user", u.username.ToString());

                    //return Redirect("/Home/Index");
                    //return RedirectToAction("Index", "home","");
                    //Ajax 前端是不会刷新的，前端需要强制跳转
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    
                    //return Json(new {Msg= "Login failed", data="error" });
                    return  Json(new { Msg = "Login failed", data = "error" });

                }


            }
            else {

                return Json("Msg", "Login failed");

            }

          


        }
    }
}